
package com.scs.application.modules.upms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.scs.application.core.global.GlobalDictService;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.CacheUtils;
import com.scs.application.modules.upms.entity.DictData;
import com.scs.application.modules.upms.mapper.DictDataMapper;
import com.scs.application.modules.upms.request.DictDataQueryRequest;
import com.scs.application.modules.upms.service.DictDataService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典数据 service 实现
 *
 */
@Slf4j
@Service
@AllArgsConstructor
public class DictDataServiceImpl extends BaseServiceImpl<DictDataMapper, DictData> implements DictDataService, InitializingBean, ApplicationRunner {

    private final GlobalDictService globalDictService;


    @Override
    public List<DictData> list(DictDataQueryRequest request) {
        List<String> excludeFields = Lists.newArrayList("creator", "modifier", "gmtCreate", "gmtModified");
        List<DictData> list = this.list(Wrappers.<DictData>query()
                .select(DictData.class, o -> !excludeFields.contains(o.getProperty()))
                .eq(request.getDictTypeId() != null, "dict_type_id", request.getDictTypeId())
                .orderByAsc("sort")
        );
        list.forEach(o -> o.setModifier(null).setGmtModified(null).setCreator(null).setGmtCreate(null));
        return list;
    }

    @Override
    public IPage<DictData> page(DictDataQueryRequest request) {
        IPage page = this.page(request.getPage(), Wrappers.<DictData>query()
                .eq(request.getDictTypeId() != null, "dict_type_id", request.getDictTypeId())
                .orderByAsc("sort")
        );
        return page;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<DictData> list = this.list(Wrappers.<DictData>query().select("dict_type_code,value,label"));

        list.stream().map(DictData::getDictTypeCode).forEach(key -> {
            CacheUtils.put(CacheUtils.SYS_CACHE,key,list.stream().filter(tmp -> tmp.getDictTypeCode().equals(key)).collect(Collectors.toList()));
        });
    }
}
